import 'package:flutter/material.dart';
import 'package:flutter_highlighter/themes/a11y-light.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:markdown_widget/config/configs.dart';
import 'package:markdown_widget/config/markdown_generator.dart';
import 'package:markdown_widget/markdown_widget.dart';
import 'package:markdown_widget/widget/blocks/container/blockquote.dart';
import 'package:markdown_widget/widget/blocks/container/table.dart';
import 'package:markdown_widget/widget/blocks/leaf/code_block.dart';
import 'package:markdown_widget/widget/blocks/leaf/link.dart';
import 'package:markdown_widget/widget/markdown_block.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:windows_demo/Utils/color_utils.dart';

import '../Widgets/MarkDownWidget/code_wrapper.dart';
import '../Widgets/MarkDownWidget/custom_node.dart';
import '../Widgets/MarkDownWidget/latex.dart';
import '../Widgets/MarkDownWidget/vedio.dart';
import 'MessageModel.dart';

class DouBao extends StatefulWidget {
  const DouBao({
    super.key,
    required this.messages,
    required this.isAnswering,
  });

  final List<MessageModel> messages;
  final bool isAnswering;


  @override
  State<DouBao> createState() => _DouBaoState();
}

class _DouBaoState extends State<DouBao> with TickerProviderStateMixin{
  final ScrollController _scrollController = ScrollController();
  // 是否展示滚动按钮
  bool showScrollButton = false;
  late final AnimationController _animationController = AnimationController(
    duration: const Duration(milliseconds: 500),
    reverseDuration: const Duration(milliseconds: 500),
    vsync: this,
  );



  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (showScrollButton == false && _scrollController.position.pixels >= 500) {
        setState(() {
          showScrollButton = true;
          _animationController.reverse();
        });
      } else if (showScrollButton == true && _scrollController.position.pixels < 500) {
        setState(() {
          showScrollButton = false;
          _animationController.forward();
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          SizedBox(height: MediaQuery.of(context).padding.top),
          buildBar(),
          Expanded(child: buildMainView()),
          buildCommand(),
        ],
      ),
    );
  }

  buildBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(10),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                SmartDialog.showToast('点击信息',displayType: SmartToastType.last);
              },
              child: const Row(
                children: [
                  SizedBox(width: 16),
                  CircleAvatar(
                    radius: 18,
                    backgroundColor: Colors.transparent,
                    backgroundImage: AssetImage(
                      'assets/images/people.png',
                    ),
                  ),
                  SizedBox(width: 5),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '刘克',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.black,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Text(
                          '1846748563@qq.com',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  buildMainView() {
    final offsetAnimation = Tween<Offset>(
      begin: const Offset(0, 0),
      end: const Offset(0, 0.13),
    ).animate(_animationController);

    codeWrapper(child, text, language) => CodeWrapperWidget(child, text, language);

    return Stack(
      children: [
        ListView(
          controller: _scrollController,
          reverse: true,
          shrinkWrap: true,
          physics: const BouncingScrollPhysics(),
          children: widget.messages.map<Widget>((MessageModel item) =>
            Column(
              crossAxisAlignment: item.isUser == 1 ? CrossAxisAlignment.end : CrossAxisAlignment.start,
              children: [
                Container(
                  padding: const EdgeInsets.all(10),
                  margin: const EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                  decoration: BoxDecoration(
                    color: item.isUser == 1 ? YZMColors.color_primary : YZMColors.color_99_20,
                    borderRadius: BorderRadius.circular(15),
                  ),
                  constraints: BoxConstraints(
                    maxWidth: MediaQuery.of(context).size.width * 0.8,
                  ),
                  child: Column(
                    crossAxisAlignment: item.isUser == 1 ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                    children: [
                      item.isUser == 1 ? SelectableText(
                        item.messageContent,
                        style: const TextStyle(
                          color: Colors.white,
                        ),
                        textAlign: TextAlign.end,
                      ) :
                      SingleChildScrollView(
                        child: MarkdownBlock(
                          data: item.messageContent,
                          config: MarkdownConfig(
                            configs: [
                              const PreConfig().copy(wrapper: codeWrapper),
                              LinkConfig(
                                style: const TextStyle(
                                  color: Colors.red,
                                  decoration: TextDecoration.underline,
                                ),
                                onTap: (url) {
                                  Uri? uri = Uri.tryParse(url);
                                  if (uri != null) {
                                    launchUrl(uri);
                                  }
                                },
                              ),
                            ],
                          ),
                          generator: MarkdownGenerator(
                            generators: [videoGeneratorWithTag, latexGenerator],
                            inlineSyntaxList: [LatexSyntax()],
                            textGenerator: (node, config, visitor) =>
                              CustomTextNode(
                                node.textContent,
                                config,
                                visitor,
                              ),
                            richTextBuilder: (span) =>
                              Text.rich(span, textScaleFactor: 1),
                            linesMargin: const EdgeInsets.all(0),
                          ),
                        ),
                      ),
                      widget.messages.indexOf(item) == 0 && item.isUser == 0 && !widget.isAnswering ?
                      Column(
                        crossAxisAlignment: item.isUser == 1 ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                        children: [
                          Container(
                            margin: const EdgeInsets.symmetric(vertical: 10),
                            color: item.isUser == 1 ? Colors.blue.shade300 : YZMColors.color_99_20,
                            height: 0.5,
                          ),
                          SingleChildScrollView(
                            physics: const BouncingScrollPhysics(),
                            scrollDirection: Axis.horizontal,
                            child: Row(
                              children: [
                                SizedBox(
                                  height: 40,
                                  child: TextButton(
                                    style: ButtonStyle(
                                      backgroundColor: MaterialStatePropertyAll(Colors.blue.shade50),
                                      shape: const MaterialStatePropertyAll(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(Radius.circular(10)),
                                        ),
                                      ),
                                    ),
                                    onPressed: () {
                                      SmartDialog.showToast('点击更好',displayType: SmartToastType.last);
                                    },
                                    child: Row(
                                      children: [
                                        Image.asset(
                                          'assets/images/thumbsup_outlined.webp',
                                          color: Colors.blue,
                                          width: 20,
                                          height: 20,
                                        ),
                                        const Text(
                                          '更好',
                                          style: TextStyle(
                                            color: Colors.blue,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 10),
                                SizedBox(
                                  height: 40,
                                  child: TextButton(
                                    style: ButtonStyle(
                                      backgroundColor: MaterialStatePropertyAll(Colors.blue.shade50),
                                      shape: const MaterialStatePropertyAll(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(Radius.circular(10)),
                                        ),
                                      ),
                                    ),
                                    onPressed: () {
                                      SmartDialog.showToast('点击更差',displayType: SmartToastType.last);
                                    },
                                    child: Row(
                                      children: [
                                        Image.asset(
                                          'assets/images/thumbsdown_outlined.webp',
                                          color: Colors.blue,
                                          width: 20,
                                          height: 20,
                                        ),
                                        const Text(
                                          '更差',
                                          style: TextStyle(
                                            color: Colors.blue,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 10),
                                SizedBox(
                                  height: 40,
                                  width: 40,
                                  child: TextButton(
                                    style: ButtonStyle(
                                      backgroundColor: MaterialStatePropertyAll(Colors.blue.shade50),
                                      shape: const MaterialStatePropertyAll(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(Radius.circular(10)),
                                        ),
                                      ),
                                    ),
                                    onPressed: () {
                                      // TTSUtil().speak(item.messageContent);
                                    },
                                    child: Image.asset(
                                      'assets/images/play_outlined.webp',
                                      color: Colors.blue,
                                      width: 20,
                                      height: 20,
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 10),
                                SizedBox(
                                  height: 40,
                                  width: 40,
                                  child: TextButton(
                                    style: ButtonStyle(
                                      backgroundColor: MaterialStatePropertyAll(Colors.blue.shade50),
                                      shape: const MaterialStatePropertyAll(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(Radius.circular(10)),
                                        ),
                                      ),
                                    ),
                                    onPressed: () {
                                      SmartDialog.showToast('点击返回之前回复',displayType: SmartToastType.last);
                                    },
                                    child: Image.asset(
                                      'assets/images/arrow_backward_outlined.webp',
                                      color: Colors.blue,
                                      width: 20,
                                      height: 20,
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 10),
                                SizedBox(
                                  height: 40,
                                  width: 40,
                                  child: TextButton(
                                    style: ButtonStyle(
                                      backgroundColor: MaterialStatePropertyAll(Colors.blue.shade50),
                                      shape: const MaterialStatePropertyAll(
                                        RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(Radius.circular(10)),
                                        ),
                                      ),
                                    ),
                                    onPressed: () {
                                      SmartDialog.showToast('点击重新加载',displayType: SmartToastType.last);
                                    },
                                    child: Image.asset(
                                      'assets/images/refresh.webp',
                                      color: Colors.blue,
                                      width: 20,
                                      height: 20,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          )
                        ],
                      ) : const SizedBox.shrink(),
                    ],
                  ),
                ),
              ],
            ),
          ).toList(),
        ),
        SlideTransition(
          position: offsetAnimation,
          child: Padding(
            padding: const EdgeInsets.only(bottom: 10),
            child: AnimatedOpacity(
              duration: const Duration(milliseconds: 500),
              opacity: showScrollButton ? 1.0 : 0.0,
              curve: Curves.ease,
              child: Align(
                alignment: Alignment.bottomCenter,
                child: FloatingActionButton(
                  mini: true,
                  backgroundColor: Colors.blue.shade50,
                  onPressed: () {
                    scroll(bottom: true);
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(10),
                    child: Image.asset(
                      'assets/images/scroll_arrow.png',
                      color: Colors.blue,
                      width: 20,
                      height: 20,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  buildCommand() {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          Expanded(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 10),
                child: Row(
                  children: [
                    SizedBox(
                      height: 40,
                      child: TextButton(
                        style: const ButtonStyle(
                          shape: MaterialStatePropertyAll(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.all(Radius.circular(15)),
                            ),
                          ),
                          side: MaterialStatePropertyAll(
                              BorderSide(
                                width: 1,
                                color: YZMColors.color_99_20,
                              )
                          ),
                        ),
                        onPressed: () {
                          scroll();
                        },
                        child: Row(
                          children: [
                            Image.asset(
                              'assets/images/command.png',
                              color: Colors.blue,
                              width: 20,
                              height: 20,
                            ),
                            const Text(
                              '前往顶部',
                              style: TextStyle(
                                color: Colors.blue,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  scroll({bool bottom = false}) {
    if (_scrollController.position.pixels != (bottom ? _scrollController.position.minScrollExtent : _scrollController.position.maxScrollExtent)) {
      _scrollController.animateTo(bottom ? _scrollController.position.minScrollExtent : _scrollController.position.maxScrollExtent, duration: const Duration(milliseconds: 200), curve: Curves.linear);
    }
  }

  buildCommandItem(String text, void Function() onPressed) {
    return SizedBox(
      height: 40,
      child: TextButton(
        style: const ButtonStyle(
          shape: MaterialStatePropertyAll(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(15)),
            ),
          ),
          side: MaterialStatePropertyAll(
            BorderSide(
              width: 1,
              color: YZMColors.color_99_20,
            ),
          ),
          overlayColor: MaterialStatePropertyAll(YZMColors.color_99_20),
        ),
        onPressed: onPressed,
        child: Row(
          children: [
            Image.asset(
              'assets/images/command.png',
              color: Colors.black,
              width: 20,
              height: 20,
            ),
            Text(
              text,
              style: const TextStyle(
                color: Colors.black,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
